package com.core.shared;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/5/26
 * Time: 17:04
 * To change this template use File | Settings | File Templates.
 */
public class MapUtils {

    /**
     * 根据map的 V 来排序
     *
     * @param map
     * @param isDesc 是否降序
     * @return
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, final boolean isDesc) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            if (isDesc) {
                return o1.getValue().compareTo(o2.getValue());
            } else {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    /**
     * 根据map的 K 来排序
     *
     * @param map
     * @param isDesc 是否降序
     * @return
     */
    public static Map<String, Object> sortByKey(Map<String, Object> map, final boolean isDesc) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<>((o1, o2) -> {
            if (isDesc) {
                return o1.compareTo(o2);
            } else {
                return o2.compareTo(o1);
            }
        });
        sortMap.putAll(map);
        return sortMap;
    }

    /**
     * 二分查找
     * 应用要求：有序排列的数组
     *
     * @param data
     * @param target
     * @return
     */
    public static long twoPointSearch(long[] data, long target) {
        int start = 0;
        int end = data.length - 1;
        while (start <= end) {
            int middleIndex = (start + end) / 2;
            if (target == data[middleIndex]) {
                return middleIndex;
            }
            if (target > data[middleIndex]) {
                start = middleIndex + 1;
            } else {
                end = middleIndex - 1;
            }
        }
        return -1;
    }

}
